package com.controller;

import com.config.FeignForAppsConfig;
import com.controller.vo.OrderItem;
import com.controller.vo.PaymentInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import utils.Utils;

import java.math.BigDecimal;
import java.util.HashMap;

@Slf4j
@RestController
public class CentralController {

    @Autowired
    FeignForAppsConfig.FeignClientForOrder order;
    @Autowired
    FeignForAppsConfig.FeignClientForPayment payment;
    @Autowired
    StreamBridge streamBridge;

/**
 // order the shirt with 5 item . then payment fail , so send back the 5 item
 // resovle1: use soft transaction , use the mq used for eventual consistency; store the release resource.
 // resovle2: use strong transaction
 */
    @RequestMapping(value = "central")
    public String central(){
        Jwt jwt = Utils.extractJwt();
        Assert.notNull(jwt,"current user have been login");
        String authorizationHeader="Bearer "+jwt.getTokenValue();
        OrderItem shirt = new OrderItem("shirt", 123);
        String forObject = order.order(authorizationHeader,shirt);

        String msg = "operation success";
        BigDecimal bigDecimal = new BigDecimal(100);
        PaymentInfo paymentInfo = new PaymentInfo("hcj", bigDecimal);
        if(forObject.equals("success")){
            String hcj = payment.payment(authorizationHeader,paymentInfo);
            if(hcj.equals("success")){
            }else{
                errorHandleForOrder(shirt);
                msg="payment operation failed";
            }
        }else{
            msg="order operation failed";
        }

        return  msg;


    }
    // order success and  payment failed then rollback the order

    private void errorHandleForOrder(OrderItem shirt){
        MessageHeaders headers = new MessageHeaders(new HashMap(){
            {
                put("from","com.controller.CentralController.central.class");
            }
        });
        Message<OrderItem> message1 = MessageBuilder.createMessage(shirt, headers);

        streamBridge.send("errorEventSupplier-out-0",message1);

    }
}
